package net.sudot.commons.security;

import net.sudot.chess.business.model.User;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.DisabledAccountException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.SimpleAccount;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.credential.CredentialsMatcher;
import org.apache.shiro.cache.CacheManager;

/**
 * 授权域
 *
 * @author tangjialin on 2017-06-14 0014.
 */
public class JwtAuthorizingRealm extends AuthorizingRealm {

    public JwtAuthorizingRealm(AuthenticationProvider authenticationProvider) {
        super(authenticationProvider);
    }

    public JwtAuthorizingRealm(CacheManager cacheManager, AuthenticationProvider authenticationProvider) {
        super(cacheManager, authenticationProvider);
    }

    public JwtAuthorizingRealm(CredentialsMatcher matcher, AuthenticationProvider authenticationProvider) {
        super(matcher, authenticationProvider);
    }

    public JwtAuthorizingRealm(CacheManager cacheManager, CredentialsMatcher matcher, AuthenticationProvider authenticationProvider) {
        super(cacheManager, matcher, authenticationProvider);
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        JwtUserAuthenticationToken token = (JwtUserAuthenticationToken) authenticationToken;
        User user = authenticationProvider.getUser(token.getPayload());
        if (user == null) { throw new UnknownAccountException(); }
        if (!Boolean.TRUE.equals(user.getEnabled())) { throw new DisabledAccountException(); }
        if (Boolean.TRUE.equals(user.getLocked())) { throw new LockedAccountException(); }
        SimpleAccount account = new SimpleAccount(user, user.getPassword(), getName());
        return account;
    }

}